import 'dart:async';

import 'package:flutter/material.dart';

class StateWidgetPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("widgets' state"),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          TextWithoutState(),
          SizedBox(
            height: 50,
          ),
          TextWithState(
            interval: 2,
          ),
        ],
      ),
    );
  }
}

class TextWithoutState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("我是一个无状态的文本widget");
  }
}

/// 一个有状态的text widget
class TextWithState extends StatefulWidget {
  final int interval;

  const TextWithState({Key key, this.interval}) : super(key: key);

  @override
  _TextWithStateState createState() => _TextWithStateState();
}

/// 一个有状态的text widget
class _TextWithStateState extends State<TextWithState> {
  String _text = "";
  Timer _timer;

  @override
  void initState() {
    _timer = Timer.periodic(Duration(seconds: widget.interval), (timer) {
      setState(() {
        _text = "我是一个有状态的widget，每${widget.interval}秒更新自己的状态：${_getCurrentTime()}";
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    _timer.cancel();
    _timer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text(_text);
  }

  String _getCurrentTime() {
    return DateTime.fromMillisecondsSinceEpoch(DateTime.now().millisecondsSinceEpoch).toString().substring(11, 19);
  }
}
